import Vue from 'vue'
import VueRouter from 'vue-router'
// vuex
import store from '@/store'
// 组件引入
const Login = () => import('@/views/Login')
const Layout = () => import('@/views/Layout')
const Home = () => import('@/views/Layout/Home')
const Question = () => import('@/views/Layout/Question')
const Video = () => import('@/views/Layout/Video')
const User = () => import('@/views/Layout/User')
const Search = () => import('@/views/Search')
const Result = () => import('@/views/Search/components/result')
const Article = () => import('@/views/Article')
const UserProfile = () => import('@/views/Layout/User/UserProfile')
const UserChat = () => import('@/views/Layout/User/UserChat')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    // 登录
    { path: '/login', component: Login },
    // layout
    { path: '/', component: Layout,
      children: [
        { path: '/', component: Home, meta: { isKeepAlive: true }},
        { path: '/question', component: Question },
        { path: '/video', component: Video },
        { path: '/user', component: User }
      ]
    },
    // 搜索
    { path: '/search', component: Search },
    // 搜索结果
    { path: '/result', name: 'result', component: Result },
    // 文章详情
    { path: '/article/:id', name: 'article', component: Article },
    // 编辑资料
    { path: '/userProfile', component: UserProfile },
    { path: '/userChat', component: UserChat }

  ]
})

const authLinks = ['/user', '/cart', 'userInfo']
router.beforeEach((to, from, next) => {
  const token = store.state.user.tokenInfo.token
  // 1. 如果目标地址需要身份认证,则验证用户是否携带token
  if (authLinks.includes(to.path)) {
    if (token) {
      next()// 有token,放行
    } else {
      // 没有token,则携带目标地址跳转登录页
      next({
        path: '/login',
        query: {
          prevPath: to.fullPath
        }
      })
    }
  } else if (to.path === '/login' && token) {
    // 2. 如果目标地址是登录页,并且用户已经携带token,则跳转首页
    next('/')
  } else {
    next()
  }
})
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
export default router
